package transport;

import java.io.IOException;
import java.net.Socket;

/**
 * BaseAgent class supports basic agent functionality.
 */
public abstract class BaseAgent implements Agent {
    protected final Protocol protocol;
    public BaseAgent(Protocol protocol) {
        this.protocol = protocol;
    }

    private boolean stopped = false;
    public synchronized boolean isRunning() {
        return started && !stopped;
    }

    private boolean started = false;
    public synchronized void start() {
        if (!started) {
            started = true;
            stopped = shouldStop = false;
            new Thread(this).run();
        }
    }

    private boolean shouldStop = false;
    public synchronized void stop() {
        shouldStop = true;
    }

    public synchronized boolean isShouldStop() {
        return shouldStop;
    }

    protected abstract void update() throws IOException;

    public void run() {
        protocol.registerAgent(this);

        while (!isShouldStop()) {
            try {
                update();
            }
            catch (IOException e) {
                e.printStackTrace();

                stop();
            }
        }

        synchronized (this) {
            stopped = true;
        }

        protocol.unregisterAgent(this);
    }
}
